package org.jicengine.io;

import java.io.*;
import javax.servlet.ServletContext;

/**
 * <p>
 * A Resource-implementation for accessing resources inside a web-application.
 * </p>
 * <p>
 * WebApplicationResource used the methods <code>ServletContext.getResource()</code> and
 * <code>ServletContext.getResourceAsStream()</code> for the job.
 * </p>
 *
 * <p>
 * Copyright (C) 2004  Timo Laitinen
 * </p>
 * @author Timo Laitinen
 * @created 2004-09-20
 * @since JICE-0.10
 */

public class WebApplicationResource extends AbstractResource implements UrlReadable  {

	private ServletContext webApplication;
	private String resourceName;

	/**
	 * @param webApplication   the ServletContext of the web-application
	 * @param resourceName     the name of the resource i.e. a path inside
	 *                         the web-app. must start with "/".
	 */
	public WebApplicationResource(ServletContext webApplication, String resourceName)
	{
		super("web-app://" + resourceName);
		this.webApplication = webApplication;
		this.resourceName = resourceName;
	}

	public ServletContext getServletContext()
	{
		return this.webApplication;
	}

	public String getResourceName()
	{
		return this.resourceName;
	}

	public java.net.URL getUrl() throws IOException
	{
		java.net.URL url = this.webApplication.getResource(getResourceName());
		if( url != null ){
			return url;
		}
		else {
			throw new IOException("Can't find web-application resource '" + getResourceName() + "'");
		}
	}

	public boolean isAvailable()
	{
		try {
			return (this.webApplication.getResource(getResourceName()) != null);
		} catch (java.net.MalformedURLException e){
			return false;
		}
	}

	public InputStream getInputStream() throws java.io.IOException
	{
		InputStream stream = this.webApplication.getResourceAsStream(getResourceName());

		if( stream != null ){
			return stream;
		}
		else {
			throw new IOException("Can't find web-application resource '" + getResourceName() + "'");
		}
	}

	public Resource getResource(String relativePath) throws java.io.IOException
	{
		return new WebApplicationResource(getServletContext(), PathResolver.getRealPath(getResourceName(), relativePath));
	}
}
